package com.gack.business.service;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.gack.business.model.Message;
import com.gack.business.model.MessagePush;
import com.gack.business.model.MessagePushUser;
import com.gack.business.model.PushSwitch;
import com.gack.business.model.SensitiveWord;
import com.gack.business.model.User;
import com.gack.business.repository.ConferenceUserRepository;
import com.gack.business.repository.MessagePushRepository;
import com.gack.business.repository.MessagePushUserRepository;
import com.gack.business.repository.MessageRepository;
import com.gack.business.repository.PushSwitchRepository;
import com.gack.business.repository.UserRepository;
import com.gack.helper.common.abstractobj.Result;
import com.gack.helper.common.util.ChangeDateTimeUtil;
import com.gack.helper.common.util.JPushRestAPI;
import com.gack.helper.common.util.sendCode;

@Service
public class MessagePushService implements MessagePushServiceInterface {
	
	@Autowired
	private MessagePushRepository messagePushRepository;
	@Autowired
	private MessagePushUserRepository messagePushUserRepository;
	@Autowired
	private MessageRepository messageRepository;
	@Autowired
	private UserRepository userRepository;
	@Autowired
	private PushSwitchRepository pushSwitchRepository;
	@PersistenceContext
	private EntityManager manager;
	@Autowired
	private ConferenceUserRepository conferenceUserRepository;
	@Autowired
	private BackLogService backLogService;
	@Transactional
	@Override
	public Result addPush(String title ,String content,Integer type, String users, String createId) throws Exception {
		String[] usernames = users.split(",");
		Result result = new Result();
		MessagePush messagePush = new MessagePush();
		messagePush.setTitle(title);
		messagePush.setContent(content);
		messagePush.setSendTime(new Date());
		messagePush.setType(type);
		messagePush.setSendTime(new Date());
		messagePush.setMesKey("00");
		MessagePush saveAfterMes = messagePushRepository.save(messagePush);
		if (saveAfterMes != null) {
			List<String> phones = null;
			if ("".equals(users)) {
				List<User> lists = userRepository.findAll();
				phones= lists.stream().map(User::getUsername).collect(Collectors.toList());
			} else {
				phones = Arrays.asList(usernames);
			}
			List<MessagePushUser> messagePushUsers = phones.stream().map(e -> new MessagePushUser(saveAfterMes.getId(),e)).collect(Collectors.toList());
			messagePushUserRepository.save(messagePushUsers);
			sendMessage(messagePush, phones, createId);
		}
		/*if (usernames == null) {
			List<User> lists = userRepository.findAll();
			List<String> phones= lists.stream().map(User::getUsername).collect(Collectors.toList());
			List<MessagePushUser> messagePushUser = phones.stream().map(e -> new MessagePushUser(saveAfterMes.getId(),toString())).collect(Collectors.toList());
			messagePushUserRepository.save(messagePushUser);
			if (saveAfterMes != null) {
				for (String username : phones) {
					messagePushUserRepository.save(new MessagePushUser(saveAfterMes.getId(), username));
				}
			}
			sendMessage(messagePush, phones, createId);
			
		}else {
			if (saveAfterMes != null) {
				for (String username : usernames) {
					messagePushUserRepository.save(new MessagePushUser(saveAfterMes.getId(), username));
				}
			}
			sendMessage(messagePush, Arrays.asList(usernames), createId);
		}*/
		
		result.setKey("success");
		result.setValue("推送成功");
		backLogService.addBackLog(createId, "推送了一条消息 messagePush的id为" + saveAfterMes.getId() );
		return result;
	}
	@Transactional
	@Override
	public void sendMessage(MessagePush messagePush, List<String> usernames, String createId) throws Exception {
		JPushRestAPI jPushRestAPI = new JPushRestAPI();
		List<PushSwitch> list = pushSwitchRepository.findAll();
		PushSwitch pushSwitch  = list.get(0);
		if (pushSwitch.getIsSwitch() == 0) {
			jPushRestAPI.setApns_production(false);
		}
		for (String username : usernames) {
			List<User> users = userRepository.findByUsername(username);
			User user = null;
			if (users != null && users.size() > 0) {
				user = userRepository.findByUsername(username).get(0);
				Message message = new Message();
				message.setTitle(messagePush.getTitle());
				message.setMessage(messagePush.getContent());
				message.setCreateId(createId);
				message.setCreatetime(new Date());
				message.setIsRead(0);
				message.setMesType(5);
				if (user != null) {
					message.setUserid(user.getId());
				}
				if (messagePush.getType() == 1) {
					message.setSendWay(1);
					sendCode.sendMessage(username, message.getMessage());
				}else if (messagePush.getType() ==2) {
					message.setSendWay(2);
				} else if (messagePush.getType() ==3) {
					message.setSendWay(3);
					jPushRestAPI.SendPush(message.getMessage(), "", "", "Default", jPushRestAPI.jsonDataByOneAlias(username));
				}
				messageRepository.save(message);
			}
			
			
		}
		
		
	}
	@Override
	public Result registerTime(String startTime, String endTime) throws Exception{
		Result result = new Result();
		String jpql = "SELECT u FROM User u WHERE 1=1";
		if (startTime != null &&! "".equals(startTime)) {
			startTime = ChangeDateTimeUtil.zExchangeUTC(startTime);
			jpql += "AND u.createtime >= '" + startTime+"'";
		}
		if (endTime != null &&! "".equals(endTime)) {
			endTime = ChangeDateTimeUtil.zExchangeUTC(endTime);
			jpql += "AND u.createtime <= '" + endTime+"'";
		}
		Query query = manager.createQuery(jpql);
		List<User> users = query.getResultList();
		if (users != null && users.size() >0) {
			List<String> usernames = users.stream().map(User::getUsername).collect(Collectors.toList());
			result.setKey("success");
			result.setValue(usernames);
			return result;
		}
		result.setKey("error");
		result.setValue(null);
		return result;
	}
	@Override
	public Result unusedOfflineMeeting() {
		Result result = new Result();
		String jpql = "select u.* from user u where u.id not in (select o.id from orders o where o.status in ('4','5','6','7','8'))";
		Query query = manager.createNativeQuery(jpql, User.class);
		List<User> users = query.getResultList();
		if (users != null && users.size() >0) {
			List<String> usernames = users.stream().map(User::getUsername).collect(Collectors.toList());
			result.setKey("success");
			result.setValue(usernames);
			return result;
		}
		result.setKey("error");
		result.setValue(null);
		return result;
	}
	@Override
	public Result unusedOnlineConference() {
		Result result = new Result();
		List<User> users = userRepository.findByJoinVideoNumEquals(0);
		if (users != null && users.size() >0) {
			List<String> usernames = users.stream().map(User::getUsername).collect(Collectors.toList());
			result.setKey("success");
			result.setValue(usernames);
			return result;
		}
		result.setKey("error");
		result.setValue(null);
		return result;
	}
	@Override
	public Result Logins(String startFrequency, String endFrequency) {
		Result result = new Result();
		String jpql = "SELECT u FROM User u WHERE u.loginNum >=" + startFrequency + "AND u.loginNum <=" + endFrequency;
		Query query = manager.createQuery(jpql);
		List<User> users = query.getResultList();
		if (users != null && users.size() >0) {
			List<String> usernames = users.stream().map(User::getUsername).collect(Collectors.toList());
			result.setKey("success");
			result.setValue(usernames);
			return result;
		}
		result.setKey("error");
		result.setValue(null);
		return result;

	}
	@Override
	public Result doImportCustomerData(HttpServletRequest request, HttpServletResponse response,
			MultipartFile dataFile)  throws Exception {
		Result result = new Result();
		InputStream in = dataFile.getInputStream();
		Workbook wb = WorkbookFactory.create(in);
		Sheet sheet = wb.getSheetAt(0);
		int totcount = sheet.getLastRowNum();
		List<String> phones = new ArrayList<>();
		for (int i = 0; i <= totcount; i++) {
			Row row = sheet.getRow(i);
			if (row != null && row.getCell(0) != null) {
				row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
				String phone = row.getCell(0).getStringCellValue().trim();
				Pattern p = Pattern.compile("^((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1})|(14[0-9]{1}))\\d{8}$");  
				Matcher m = p.matcher(phone);
				if (m.matches()) {
					phones.add(phone);
				}
				
			}
		}
		if (phones != null && phones.size() >0) {
			result.setKey("success");
			result.setValue(phones);
		} else {
			result.setKey("error");
			result.setValue("导入失败");
		}
		
		
		return result;
	}

	

}
